
package com.lzx.adx.report.controller.v1.baidu;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.baidu.BaiduRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.UrlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 媒体：百度搜索
 * 媒体接口文档 https://dev2.baidu.com/content?sceneType=0&pageId=101213&nodeId=663&subhead=
 * 转化追踪下
 * 产品：盒马剧场
 */
@RequestMapping("/baidu/jym")
@RestController
@Slf4j
@RequiredArgsConstructor
public class BaiduJymReportController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(BaiduRequest baiduRequest, HttpServletRequest request) {
        log.info("接收到百度到金易木的请求参数为{}", JsonUtils.toJsonString(baiduRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(baiduRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(baiduRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportDTO.setImei(null);
        reportDTO.setImeiSum(baiduRequest.getImei());
        reportDTO.setOaidSum(baiduRequest.getOaidMd5());
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });

        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(baiduRequest.getDspId());
        //3.处理参数和URL
        String finalUrl = UrlUtil.covertAllJymUrl(accountDTO, reportDTO);
        log.info("账户号为{}完整的百度到金易木请求地址为{}", baiduRequest.getDspId(), finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账户号为{}完整的百度到金易木请求响应结果为{}", baiduRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());

    }


    /**
     * 盒马剧场
     *

     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/hz/callback")
    public ResponseEntity hzCallBackUrl(String clickId) throws Exception {
        //金易木只有激活
        String eventType = "1";
        log.info("百度收到赫兹-金易木回调信息，请求流水号{}", clickId);
        if (StringUtils.isBlank(clickId)) {
            log.info("百度收到赫兹-金易木回调信息,请求参数异常不做处理");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", clickId);
        List<ReportDTO> list = reportService.list(params);
        long currentTimeMillis = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(eventType);
            reportDTO.setResultTime(String.valueOf(currentTimeMillis));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,eventType);
        } else {
            log.error("当前流水号{}，系统当前不存在", clickId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);

        //如果不为空，且sspExtend
        Double per = jsonObject.getDouble("per");
        if (Objects.nonNull(per)) {
            if(!AdPerUtil.randomPer(per)) {
                log.info("账户id{} 流水号为 {} 超出了比例外 不做回传", reportDTO.getDspId(), reportDTO.getBizRequestId());
                return ResponseEntity.ok(new Result());
            }
        }
        String callback = reportDTO.getCallback();
        String decode = URLUtil.decode(callback);
        //解码 并替换数据
        String replace = decode.replace("{{ATYPE}}", "activate").replace("{{AVALUE}}", "0");
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("a_time", currentTimeMillis / 1000);
        paramsReq.put("join_type", "OAID");
        log.info("账户id{} 当前流水号{}赫兹-金易木回传百度原始callback{},自定义参数 {}", reportDTO.getDspId(), clickId, replace, JsonUtils.toJsonString(paramsReq));
        String finalUrl = replace + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        HttpRequest body = HttpUtil.createGet(finalUrl);
        String result = body.execute().body();
        log.info("账户id{} 当前流水号{}赫兹-金易木回传百度响应结果{}", reportDTO.getDspId(), clickId, result);
        return ResponseEntity.ok(new Result());
    }




}
